#!/usr/bin/env python
# -*- coding: utf-8 -*-

import functools
import socket
import time
from thrift.transport import TSocket
from thrift.transport import TTransport
from dm_py_util import INFO_LOG


class ThriftWrap(object):
    '''
    Thrift 通用client包装类
    '''

    def __init__(self, transport, protocol, client):
        '''
        transport: thrift.transport 类型
        protol: thrift.protocol 类型
        client: thrift实例的client类型
        '''
        self.transport_class = transport
        self.protocol_class = protocol
        self.client_class = client

    def connect(self, host, port):
        self.host = host
        self.port = port
        socket = TSocket.TSocket(host, port)
        self.transport = self.transport_class(socket)
        protocol = self.protocol_class(self.transport)
        self.agent = self.client_class(protocol)
        self.__reconnect()

    def __reconnect(self):
        self.transport.close()
        self.transport.open()
        INFO_LOG("%r connect to %s:%s success" %
                 (self.client_class.__name__, self.host, self.port))

    def __getattr__(self, method):
        return functools.partial(self.__wrap, method)

    def __wrap(self, method, *args, **kwargs):
        '''
        重试一次
        '''
        start = time.time()
        f = getattr(self.agent, method)
        try:
            try:
                return f(*args, **kwargs)
            except (TTransport.TTransportException, socket.error):
                self.__reconnect()
            return f(*args, **kwargs)
        finally:
            INFO_LOG('remote server responses time %s' %
                     (time.time() - start))


if __name__ == '__main__':
    from thrift.protocol import TBinaryProtocol
    import Bill.BillService
    from Bill.ttypes import BillContent, GiftContent, BalanceContent
    # from user.ttypes import *
    c = ThriftWrap(TTransport.TBufferedTransport,
                   TBinaryProtocol.TBinaryProtocol, Bill.BillService.Client)
    c.connect('101.201.109.140', 2060)

    def test_send_gift():
        now = time.time()
        seq_result = c.getSeqFromBill(107383, 1)
        bill_id = seq_result.bill_id
        ctx = GiftContent()
        ctx.bill_id = bill_id
        ctx.source_type = 1
        ctx.send_uid = 107393
        ctx.send_gold = 100
        ctx.recv_uid = 106839
        ctx.recv_point = 100
        ctx.source_desc = '测试送礼100个映票'
        ctx.trans_time = int(time.time())
        print ctx
        print c.givingGift(ctx)
        print time.time() - now

    def test_balance():
        b = BalanceContent()
        b.uid = 107393
        b.source_type = 1
        print b
        print c.queryBalance(b)

    def test_update_money():
        seq_result = c.getSeqFromBill(107383, 1)
        bill_id = seq_result.bill_id
        ctx = BillContent()
        ctx.bill_id = bill_id
        ctx.source_type = 1
        ctx.uid = 107393
        ctx.gold = 1000000
        ctx.point = 1000000
        ctx.souce_desc = '测试增加金币和映票'
        ctx.trans_time = int(time.time())
        print c.updateSingleUserMoney(ctx)

    # logging.basicConfig(level=logging.DEBUG,
    #                     format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
    #                     datefmt='%a, %d %b %Y %H:%M:%S',
    #                     filename='myapp.log',
    #                     filemode='w')

    test_send_gift()
    # test_balance()
    test_update_money()
    # test_balance()
